<div class="bjui-pageHeader">
    <form id="pagerForm" data-toggle="ajaxsearch" action="{:U('index')}" method="post">
        <div class="alert alert-info search-inline"><i class="fa fa-info-circle"></i> {$express.name}</div>
        <div class="pull-right">
            <!--<a href="{:U('invoiceSn')}" data-icon="edit" data-toggle="dialog" data-mask="true" class="btn btn-blue" data-width="400" data-height="200">首个发票号码</a>-->
            <div role="group" class="btn-group">
                <select name="choosePrint" data-toggle="selectpicker" class="printList">
                    <option value="">选择打印机</option>
                </select>
            </div>
            <div class="btn-group">
                <button type="button" class="btn-default dropdown-toggle" data-toggle="dropdown" data-icon="copy">
                    批量操作<span
                        class="caret"></span></button>
                <ul class="dropdown-menu right" role="menu">
                    <li><a data-group="ids" data-idname="ids" data-confirm-msg="确定要批量打印选中项吗？" data-toggle="doajaxchecked" href="{:U('getPrintCodeAll')}"  data-callback="batchPrint{:I('get.navTabId')}" >批量打印</a></li>
                </ul>
            </div>
        </div>
    </form>
</div>
<div class="bjui-pageContent tableContent">
    <form action="{:U('edit')}" class="pageForm" data-toggle="validate" method="post">
        <table class="table table-bordered table-hover table-striped table-top" data-selected-multi="true">
            <thead>
            <tr>
                <!-- 选择 	出库单号 	系统订单号 	快递单号-连号-同号 	收货人 	收货地址 	指定快递   -->
                <th><label class="control-label"><input type="checkbox" class="checkboxCtrl" data-group="ids"
                                                        data-toggle="icheck" checked>选择</label></th>
                <th data-order-field="outbound_sn" align="center">出库单号</th>
                <th data-order-field="order_sn" align="center">系统订单号</th>
                <th align="center">快递单号 <label class="control-label"><input type="checkbox" class="checkboxCtrl"
                                                                            name="consecutive"
                                                                            data-toggle="icheck">连号</label></th>
                <th align="center">收货人</th>
                <th align="center">收货地址</th>
                <th align="center">指定快递</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach($list as $arr):?>
            <tr>
                <td><input type="checkbox" name="ids" data-toggle="icheck" value="{$arr.order_id}" checked></td>
                <td style="display: none;"><input type="text" name="list[{$arr.order_id}][order_id]"
                                                  value="{$arr.order_id}" disabled></td>
                <!-- 出库单号 -->
                <td align="center">{$arr.outbound_sn}</td>
                <!-- 系统订单号 -->
                <td align="center">{$arr.order_sn}</td>
                <!-- 快递单号-连号-同号 -->
                <td align="center">
                    <?php if($express['rule']):?>
                    <input type="text" name="list[{$arr.order_id}][courie_number]" value="{$arr.courie_number}"
                           class="form-control" data-rule="required,express"
                           data-rule-express="[{$express.rule}, '当前快递单号不符合规则']">
                   <?php else:?>
                    <input type="text" name="list[{$arr.order_id}][courie_number]" value="{$arr.courie_number}"
                           class="form-control" data-rule="required">
                   <?php endif;?>
                </td>
                <!-- 收货人 -->
                <td align="center">{$arr.user_name}</td>
                <!-- 收货地址 -->
                <td align="center">{$arr.address}
                    <?php if($arr['status']==EXPRESS_PRINT_FAIL):?>
                    <div class="red">(打印失败, 请重新打印)</div>
                    <?php elseif($arr['status']==EXPRESS_PRINT_SUCCESS):?>
                    <div class="blue">(已打印，请检查是否重复打印)</div>
                    <?php endif;?>
                </td>
                <!-- 指定快递 -->
                <td>
                <a class="btn btn-green" href="{:U('getPrintCode?orderId='.$arr['order_id'])}" data-toggle="doajax" data-callback="preview{:I('get.navTabId')}">预览</a>
                    <!--<a class="btn btn-red" data-toggle="navtab"
                       data-options="{id:'Print{$arr['order_id']}', url:'{:U('orderPrintTemplate?navTabId=Print'.$arr['order_id'].'&expressId='.$express['id'].'&orderId='.$arr['order_id'])}', reloadWarn:'已打开业务页面，确认将重新载入?', title:'{$arr.name}-打印模版设计'}">打印模版设计</a>-->
                </td>
            </tr>
            <?php endforeach;?>
            </tbody>
        </table>
    </form>
</div>
<div class="bjui-pageFooter">
    <ul>
        <li>
            <button type="button" class="btn-close" data-icon="close">取消</button>
        </li>
        <li>
            <button type="submit" class="btn-default" data-icon="save">保存快递单号</button>
        </li>
    </ul>
</div>
<object id="LODOP_OB{:I('get.navTabId')}" classid="clsid:2105C259-1E0C-4534-8141-A753534CB4CA" width=0 height=0>
    <embed id="LODOP_EM{:I('get.navTabId')}" TYPE="application/x-print-lodop" PLUGINSPAGE="install_lodop32.exe" width=0 height=0>
</object>
<script>
/* 全局变量 */
var Exp_Name{:I('get.navTabId')} = "{$express.name}".toUpperCase();
var defaultPrint{:I('get.navTabId')} = "{$express.default_print}";
var BATCHLODOP{:I('get.navTabId')} = getLodop(document.getElementById("LODOP_OB{:I('get.navTabId')}"), document.getElementById("LODOP_EM{:I('get.navTabId')}"));
// var printIndex;     // 默认打印机索引
/**
 *  显示页面时操作
 */
$(document).ready(function () {
    /* 加载打印机下拉菜单 */
    var optionString = getPrinterName(BATCHLODOP{:I('get.navTabId')}, defaultPrint{:I('get.navTabId')}, true);
    $('.in select[name=choosePrint]').append(optionString);
    $('.in .printList').selectpicker('refresh');
    /* END-加载打印机下拉菜单 */
//    setPrintInit{:I('get.navTabId')}()     // 指定打印机
})

/* 预览打印 */
$(".in select[name=choosePrint]").change(function(){
    setPrintInit{:I('get.navTabId')}()
})

/**
 *  获取选择的复选框对应的快递单输入框
 */
function getChooseConsecutive{:I('get.navTabId')}() {
    return $(".in input[type=checkbox][name=ids]:checked").parent().parent().parent().find("input[type=text][name$='[courie_number]']");
}

/**
 * [preview{:I('get.navTabId')} 预览回调函数]
 * @param  {[type]} result [description]
 * @return {[type]}        [description]
 */
function preview{:I('get.navTabId')}(result){
    if(!setPrintInit{:I('get.navTabId')}()){
        return false;
    }
    var LODOP = BATCHLODOP{:I('get.navTabId')};
    if(result && result.print_code){
        result.print_code += "\r\n BATCHLODOP{:I('get.navTabId')}.PREVIEW()";
        eval(result.print_code);
        return;
    }
    console.log(result);
    $(this).alertmsg('warn', "预览打印代码不存在!");
}

/**
 * [setPrintInit{:I('get.navTabId')} 打印机初始化]
 */
function setPrintInit{:I('get.navTabId')}(){
    BATCHLODOP{:I('get.navTabId')}.SET_LICENSES(LICENSES_NAME, LICENSES_KEY, "", "");   // 打印控件授权
    BATCHLODOP{:I('get.navTabId')}.SET_PRINT_PAGESIZE("1","{$express.print_width|default='0'}mm","{$express.print_height|default='0'}mm","信纸");      // 初始化控件
    BATCHLODOP{:I('get.navTabId')}.SET_PRINT_STYLE("FontSize",12);
    var printIndex = $('.in select[name=choosePrint] option:selected').val();
    var printName = $('.in select[name=choosePrint] option:selected').html();
    var LodopPrintName = BATCHLODOP{:I('get.navTabId')}.GET_PRINTER_NAME(printIndex);
    if(printName != LodopPrintName){        // 防止打印控件获取数据异常
        $(this).alertmsg('error', '您当前的打印机数据异常, 请重载页面后再操作!');
        return false;
    }
    if(printIndex == ''){
        $(this).alertmsg('error', '请选择打印机');
        return false;
    }
    BATCHLODOP{:I('get.navTabId')}.SET_PRINTER_INDEX(printIndex);        // 指定打印机
    return true;
}


/**
 *  批量打印
 */
function batchPrint{:I('get.navTabId')}(result){
    if(!setPrintInit{:I('get.navTabId')}()){
        return false;
    }
    console.log(result);
    var failResult = [];    // 失败的订单返回数据
    var failString = '';    // 失败的订单返回消息
    for(var i in result){
        if(result[i].print_code){
            if(!setPrintInit{:I('get.navTabId')}()){
                return false;
            }
            var LODOP = BATCHLODOP{:I('get.navTabId')};
            result[i].print_code += "\r\n var printResult = LODOP.PRINT()"
            eval(result[i].print_code);
            console.log(printResult);
            /* STATUS更新打印状态 */
            var data = {};
            data['order_id'] = result[i].order_id;
            data['isPrint'] = printResult;
            $.ajax({
                type: "POST",
                url: "{:U('editPrintStatus')}",
                data: data,
                success: function(data){
                    if(!data || data.statusCode==300){   // 打印失败情况
                        $(this).alertmsg('error', '当前订单'+result[i].order_no+'打印失败');
                        printResult = false;        // 保证打印机结果
                    }
                }
            });
            /* END-更新打印状态 */
            if(!printResult){   // 打印失败情况则停止打印
                return;
            }

        }else{
            failResult[i] = result[i];
            failString += '系统订单号:'+result[i].order_sn+'打印失败<br/>';
        }
    }
    if(failResult.length>0){
        $(this).alertmsg('error', failString+'可能对应打印代码不存在');
    }
    $.CurrentNavtab.navtab('reload');          // 刷新当前窗口
}

/**
 * 批量打印检测

function batchCheck(){
    var consecutiveList = getChooseConsecutive{:I('get.navTabId')}();   // 复选框被选择的快递输入文本框
    var batchFailNumber = 0;        // 批量检测失败的数量
    if(consecutiveList.length>0){
        consecutiveList.each(function(i){
            if($.trim($(this).val())==''){
                batchFailNumber++
            }
        })
    }
    if(batchFailNumber>0){
        $(this).alertmsg('error', '快递单号不能为空!');
        return false;
    }
}
*/

/**
 *  选择复选框效果
 */
$(".in input[type=checkbox][name=ids]").on('ifChecked',function () {
    $(this).parent().parent().parent().find("input[name!=ids]").attr("disabled", false);
}).on('ifUnchecked', function () {
    $(this).parent().parent().parent().find("input[name!=ids]").attr("disabled", true);
})


/**
 * [点击连号]
 * @param  {[type]} ) {               var consecutiveList [description]
 * @return {[type]}   [description]
 */
$(".in input[type=checkbox][name=consecutive]").on('ifChecked',function () {
    var consecutiveList = getChooseConsecutive{:I('get.navTabId')}();   // 复选框被选择的快递输入文本框
    console.log(consecutiveList.length);
    // 被选择的第一个复选框的订单输入input必须含有内容

    if (consecutiveList.length == 0) {
        $(this).alertmsg('info', '当前没有选项', {title: '提示'})
        $(".in input[type=checkbox][name=consecutive]").iCheck('uncheck');
        return false;
    }

    if (typeof consecutiveList == 'undefined' || consecutiveList[0].value == "") {
        $(this).alertmsg('info', '请输入第一个快递单号', {title: '提示'})
        consecutiveList[0].focus();
        $(".in input[type=checkbox][name=consecutive]").iCheck('uncheck');
        return false;
    }
    var Exp_Num_0 = Trim(consecutiveList[0].value);                             // 获取第一个快递单号输入框
//        var Exp_Name{:I('get.navTabId')} = $(".in input[name=expressName]").val().toUpperCase();        // 获取快递方式
    var isNew = 0;


    var x = 0;      // 特殊标记数量
    var y = 0;      // 特殊标记数量
    //开始有字母的单号，包括0（如：EM、EM0）
    for (var i = 0; i < Exp_Num_0.length; i++) {
        if (isNum(Mid(Exp_Num_0, i, 1)) && Mid(Exp_Num_0, i, 1) != "0") {
            break;
        }
        x++;
    }
    //结束有字母的单号
    for (var i = Exp_Num_0.length - 1; i >= 0; i--) {
        if (isNum(Mid(Exp_Num_0, i, 1))) {
            break;
        }
        y++;
    }

    //新EMS前后两位原字母现在改数字，更新郑盛表 2013-01-02
    if (Exp_Name{:I('get.navTabId')}.indexOf("EMS") >= 0) {     // 编辑EMS
        x = 2;
        y = 2;
    }

    //开始字母
    var Exp_Num_1 = Left(Exp_Num_0, x);             // 获取开始的字符
    if (Exp_Num_1 == null) Exp_Num_1 = "";
    //结束字母
    var Exp_Num_3 = Right(Exp_Num_0, y);             // 获取结束的字符
    if (Exp_Num_3 == null) Exp_Num_3 = "";

    //EMS、顺丰、宅急送、星晨 最后一位数字是校验码，要去掉，然后动态生成，具体请查看  Sys_CommFun.js ==> get_Exp_Num_No
    if (Exp_Name{:I('get.navTabId')}.indexOf("EMS") >= 0 || Exp_Name{:I('get.navTabId')}.indexOf("E邮宝") >= 0 || Exp_Name{:I('get.navTabId')}.indexOf("顺丰") >= 0 || (isNew == "0" && Exp_Name{:I('get.navTabId')}.indexOf("宅急送") >= 0) || Exp_Name{:I('get.navTabId')}.indexOf("星晨") >= 0 || Exp_Name{:I('get.navTabId')}.indexOf("联邦") >= 0) {
        y++;
    }

    //中间连续的数字
    var Exp_Num_2 = Mid(Exp_Num_0, x, Exp_Num_0.length - x - y);
    var old_Exp_Num2_Length = Exp_Num_2.length;

    if (isNum(Exp_Num_2) == false || Exp_Num_2 == "") {
        $(this).alertmsg('info', '第一个快递单号不是数字或长度不正确，不能连号！', {title: '提示'})
        consecutiveList[0].focus();
        return false;
    }

    Exp_Num_2 = Number(Exp_Num_2);
    //记录原长度，跟自动累加后的长度对比
    var Exp_Num_2_oLength = Exp_Num_2.toString().length;
    for (var i = 1; consecutiveList.length > i; i++) {
        Exp_Num_2 += 1;
        var Exp_Num_2_Length = Exp_Num_2.toString().length;
        if (Exp_Num_2_oLength < Exp_Num_2_Length) {
            //位数进了，去掉0，例如单号：EM099999990CS，则 Exp_Num_1 = EM0，下一个单号为：EM100000003CS，则 Exp_Num_1 = EM
            if (Right(Exp_Num_1, 1) == "0") {
                Exp_Num_1 = Left(Exp_Num_1, Exp_Num_1.length - 1);
            }
            Exp_Num_2_oLength = Exp_Num_2_Length;
        }

        //开始字母 + 累加后的数字 + 验证码 + 结束字母
        var n_Exp_Num_2 = Exp_Num_2;
        //由于原快递号中间有数字会去掉以0开头的字符，这个补回0
        if (old_Exp_Num2_Length > Exp_Num_2.toString().length) {
            n_Exp_Num_2 = Left("0000000", old_Exp_Num2_Length - Exp_Num_2.toString().length) + Exp_Num_2;
        }
        if (isNew == "1" && Exp_Name{:I('get.navTabId')}.indexOf("宅急送") >= 0) {
            consecutiveList[i].value = Exp_Num_1 + n_Exp_Num_2.toString() + Exp_Num_3;
        } else {
            consecutiveList[i].value = Exp_Num_1 + n_Exp_Num_2.toString() + get_Exp_Num_No(Exp_Num_2, Exp_Name{:I('get.navTabId')}, consecutiveList[i - 1].value) + Exp_Num_3;
        }
    }
}).on('ifUnchecked', function () {
    var consecutiveList = getChooseConsecutive{:I('get.navTabId')}();
    var consecutiveContent = typeof consecutiveList[0] != 'undefined' ? consecutiveList[0].value : '';
    consecutiveList.val('');    // 情况快递单号
    if (consecutiveContent) {
        consecutiveList[0].value = consecutiveContent;
    }
})





</script>

